# Install hook code here
require 'fileutils'
require 'find'

this_dir        = File.dirname(__FILE__)
asset_dir       = this_dir + '/assets/'
controller_dir  = this_dir + '/../../../app/controllers/'
helper_dir      = this_dir + '/../../../app/helpers/'
model_dir       = this_dir + '/../../../app/models/'
script_dir      = this_dir + '/../../../script/generate'
config_dir      = this_dir + '/../../../config/'
migration_dir   = this_dir + '/../../../db/migrate/'
view_dir        = this_dir + '/../../../app/views/'
base_dir        = this_dir + '/../../../'
settings_view_dir = view_dir + 'settings/'


FileUtils.mkdir( settings_view_dir )
FileUtils.cp(asset_dir + 'edit.html.erb', settings_view_dir)
FileUtils.cp(asset_dir + 'index.html.erb', settings_view_dir)
FileUtils.cp(asset_dir + 'new.html.erb', settings_view_dir)
FileUtils.cp(asset_dir + 'show.html.erb', settings_view_dir)

FileUtils.cp(asset_dir + '/settings_helper.rb', helper_dir)
FileUtils.cp(asset_dir + '/setting.rb', model_dir)
FileUtils.cp(asset_dir + '/settings_controller.rb', controller_dir)

new_lines = []
File.open(config_dir + 'routes.rb').each { |line|
    new_lines.push(line)
    if line.include? "ActionController::Routing::Routes.draw do |map|"
      new_lines.push("  map.resources :settings")
    end
}
f = File.open(config_dir + 'routes.rb', "w+")
f.puts(new_lines)
f.close

puts `ruby #{script_dir} migration create_settings`


Find.find(migration_dir) do |path|
  #puts path
  if  File.basename(path).include? "_create_settings.rb"
    puts "detected" + path
    FileUtils.cp(asset_dir + 'migration.rb', path)
    break
  end
end

puts `cd #{base_dir} && rake db:migrate`